<template>
  <el-row>
    <el-card>
      <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item :label="tableText['stage']">
          <el-select v-model="searchForm.stageIdList" multiple clearable collapse-tags>
            <el-option
              v-for="item in stageData"
              :key="item.id"
              :label="item.flowName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="tableText['operate']">
          <el-select v-model="searchForm.operationStatus" @change="operationChange">
            <el-option
              v-for="item in tableText['operateData']"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="rejectState" :label="tableText['reason']">
          <el-select v-model="searchForm.reject" multiple clearable collapse-tags>
            <el-option
              v-for="item in listAuditRejectDescData"
              :key="JSON.stringify(item)"
              :label="item['rejectDesc']"
              :value="JSON.stringify(item)"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="tableText['operateTime']">
          <el-date-picker
            v-model="time"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="tableText['letterOrderNo']">
          <el-input v-model="searchForm.creditOrderNo" clearable :placeholder="$t('common.input')" :maxlength="50" />
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
          <el-button :disabled="!(totalNumber > 0)" @click="exportList">
            {{ $t('common.ex') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        style="width: 100%"
      >
        <el-table-column
          prop="creditOrderNo"
          :label="tableText['letterOrderNo']"
          min-width="180"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="auth(scope.row)">
              {{ scope.row.creditOrderNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="stageName"
          :label="tableText['stage']"
          min-width="150"
        />
        <el-table-column
          prop="operationResult"
          :label="tableText['operate']"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['operationResult']) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="auditRejectDsec"
          :label="tableText['reason']"
          min-width="150"
        />
        <el-table-column
          prop="operationRemark"
          :label="tableText['remarks']"
          min-width="200"
        />
        <el-table-column
          prop="createUserName"
          :label="tableText['operator']"
          min-width="100"
        />
        <el-table-column
          prop="createTime"
          :label="tableText['operateTime']"
          min-width="170"
        />
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </el-row>
</template>

<script>
import { creditAuditRecordDetail, creditAuditRecordDetailExport, listAuditStage, listAuditRejectDesc } from '@/api/risk'
import { formatDate, ObjToQueryString } from '@/utils/method'
export default {
  name: 'LetterRecord',
  data() {
    return {
      loading: true,
      tableData: [],
      stageData: [],
      rejectState: true,
      listAuditRejectDescData: [],
      tableText: {},
      time: [new Date(), new Date()],
      totalNumber: 0,
      searchForm: this.params()
    }
  },
  mounted() {
    this.tableText = this.$t('riskReport.letterRecord')
    this.getStageData()
    this.getRejectDescData()
    setTimeout(() => {
      this.getData()
    }, 100)
  },
  methods: {
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        stageIdList: [],
        operationStatus: '',
        reject: [],
        creditOrderNo: null,
        timeStart: null,
        timeEnd: null
      }
    },
    getStageData() {
      listAuditStage()
        .then(res => {
          if (res.success) {
            this.stageData = res.data
            this.searchForm.stageIdList = []
            this.stageData.forEach(v => {
              this.searchForm.stageIdList.push(v['id'])
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getRejectDescData() {
      listAuditRejectDesc()
        .then(res => {
          if (res.success) {
            this.listAuditRejectDescData = res.data
            this.searchForm.reject = []
            this.listAuditRejectDescData.forEach(v => {
              this.searchForm.reject.push(JSON.stringify(v))
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    reset() {
      this.time = [new Date(), new Date()]
      this.searchForm = this.params()
      this.stageData.forEach(v => {
        this.searchForm.stageIdList.push(v['id'])
      })
      this.listAuditRejectDescData.forEach(v => {
        this.searchForm.reject.push(JSON.stringify(v))
      })
      this.getData()
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    getData() {
      this.loading = true
      creditAuditRecordDetail(this.searchData())
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    searchData() {
      const data = {
        creditOrderNo: this.searchForm.creditOrderNo,
        operationStatus: this.searchForm.operationStatus,
        stageIdList: this.searchForm.stageIdList,
        pageSize: this.searchForm.pageSize,
        currentPage: this.searchForm.currentPage
      }
      if (this.time && this.time.length > 1) {
        data['timeStart'] = formatDate(new Date(this.time[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['timeEnd'] = formatDate(new Date(this.time[1]), 'yyyy-MM-dd') + ' 23:59:59'
      } else {
        data['timeStart'] = null
        data['timeEnd'] = null
      }
      if (this.rejectState && this.searchForm.reject && this.searchForm.reject[0]) {
        if (this.searchForm.reject.length === this.listAuditRejectDescData.length) {
          data['aiRejectIdList'] = []
          data['auditRejectIdList'] = []
        } else {
          const arr = this.searchForm.reject
          data['aiRejectIdList'] = []
          data['auditRejectIdList'] = []
          arr.forEach(v => {
            if (JSON.parse(v)['type'] === 0) {
              data['aiRejectIdList'].push(JSON.parse(v)['rejectId'])
            }
            if (JSON.parse(v)['type'] === 1) {
              data['auditRejectIdList'].push(JSON.parse(v)['rejectId'])
            }
          })
        }
      }
      return data
    },
    exportList() {
      creditAuditRecordDetailExport(this.searchData())
    },
    setValue(data) {
      if (data === -3) {
        return this.tableText['machineReview']
      } else if (data >= 0) {
        const obj = this.tableText['operateData'].filter(v => {
          return v['value'] === data
        })
        return (obj && obj[0] && obj[0]['desc']) ? obj[0]['desc'] : ''
      }
    },
    operationChange(data) {
      this.rejectState = data === '' || data === 3 || data === 5
    },
    auth(item) {
      const paramData = {
        from: 'letterRecord',
        status: item['status'],
        userId: item['userId'],
        orderId: item['id']
      }
      const para = ObjToQueryString(paramData)
      window.open(`${window.location.origin + window.location.pathname}#/usr/auth?${para}`, '_blank')
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  margin: 10px;
}
</style>
